<?php


namespace logic\cyf;


use frontend\models\cyf\Address;
use frontend\models\cyf\FlashSale;
use frontend\models\cyf\Goods;
use frontend\models\cyf\LogOperation;
use frontend\models\cyf\OrderLog;

class SeckillLogic
{
    public static function list()
    {
        $data = FlashSale::list();
        if(!$data) throw new \Exception('操作失败');
        return $data;
    }

    /**
     * 添加秒杀商品
     * @param $params
     * @return bool
     * @throws \Exception
     * @cyf
     */
    public static function create($params)
    {
        $goods = Goods::goodsDetail($params['goods_id']);//获取商品信息
        $key = date('YmdHis') . $params['goods_id'];//秒杀商品唯一标识
        $params = [
            'key' => $key,
            'goods_id' => $goods['id'],
            'name' => $goods['name'],
            'is_top' => $params['is_top'],
            'stocks' => $params['stocks'],
            'pic_url' => $goods['img'],
            'flash_price' => $params['flash_price'],
            'status' => $params['status']
        ];
        $res =FlashSale::create($params);//添加秒杀商品
        if(!$res) throw new \Exception('添加秒杀商品失败');
        $redis = \Yii::$app->redis;
        $redis_key = 'goods'.$params['goods_id'];
        $redis->select(4);
        for($i=0;$i<$params['stocks'];$i++){
            $redis->lpush($redis_key,1);
        }
        return true;
    }

    /**
     * 商品详情
     * @param $goodsId
     * @cyf
     */
    public static function detail($goodsId)
    {
        $goods = FlashSale::detail($goodsId);
        if(!$goods) throw new \Exception('秒杀商品不纯存在');
        return $goods;
    }

    /**
     * 开始秒杀
     * @param $params
     * @throws \Exception
     * @cyf
     */
    public static function killGoods($params)
    {
        $goods = FlashSale::flashOne($params['id']);
        $time = date('Y-m-d H:i:s');
        if($time < $goods['start_time']) throw new \Exception('秒杀还没开始');
        if($time > $goods['end_time']) throw new \Exception('秒杀已经结束');
       $redis_key = 'goods'.$params['id'];
       $redis = \Yii::$app->redis;
       $redis->select(4);
       //判断是否还有秒杀商品
       if(!$redis->llen($redis_key)) throw new \Exception('没有商品了哦!!!');
       $res = $redis->lpop($redis_key);
       if(!$res) throw new \Exception('秒杀失败');
        $transaction = \Yii::$app->db->beginTransaction();//开启事务
       $killGoods = FlashSale::killGoods($params['id']);//秒杀商品减一
        if($killGoods != 1){
            $transaction->rollBack(); throw new \Exception('减库存失败');
        }
        $order = OrderLogic::createOrder($params);//生成订单
        if($order == false){
            $transaction->rollBack();
            throw new \Exception('生成订单失败');
        }
        $log = [
            'order_id'=>$order,
          'user'=>$params['user_id'],
            'action'=>'用户秒杀商品',
            'result'=>'秒杀成功',
            'note'=>''
        ];
        $log = OrderLog::create($log);//记录日志
        $transaction->commit();
        return $order;
    }
}